package com.jic.point.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jic.common.base.vo.PageResult;
import com.jic.point.constant.consist.ResponseCode;
import com.jic.point.exception.AppRuntimeException;
import com.jic.point.mapper.ConfBdMapper;
import com.jic.point.mapper.ConfBdPlatfromRelaMapper;
import com.jic.point.mapper.ConfPlatformApplyMapper;
import com.jic.point.mapper.ConfPlatformMapper;
import com.jic.point.model.entity.*;
import com.jic.point.model.vo.response.ConfFaultTreeResponse;
import com.jic.point.rest.request.SignData;
import com.jic.point.service.ConfPlatformService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
 * 接口实现类
 *
 * @author : tzc
 * @version : v1.0.0
 * @email :
 * @since : 2020-03-09 10:12:20
 */
@Service
@Slf4j
public class ConfPlatformServiceImpl implements ConfPlatformService {

	@Resource
	private ConfPlatformMapper mapper;
	@Resource
    ConfPlatformApplyMapper applyMapper;

	@Resource
    ConfBdPlatfromRelaMapper relaMapper;

	@Resource
    ConfBdMapper confBdMapper;
	/**
	 * 新增记录
	 *
	 * @param request 需要保存的入参实体类
	 * @return int 是否保存成功
	 */
	@Override
	public int save(ConfPlatform request) {
        request.setCreator(request.getAdminOperate().getOperator());//创建用户—当前登陆用户id
        request.setCreateTime(new Date());//创建时间 获取系统当前时间
        request.setCreator(request.getAdminOperate().getOperator());
        log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(request));
        //平台编码默认生成
        Date date = new Date();
        //设置要获取到什么样的时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
        //获取String类型的时间
        String format = sdf.format(date);
        String code = "PF" + format;
        //插入到BD部门和平台关联列表
        ConfBdPlatfromRela confBdPlatfromRela = new ConfBdPlatfromRela();
        BeanUtils.copyProperties(request, confBdPlatfromRela);
        confBdPlatfromRela.setPlatformCode(code);//平台编码
        confBdPlatfromRela.setPlatformName(request.getName());//平台
        confBdPlatfromRela.setDeleteFlag(0);
        confBdPlatfromRela.setType(2);//结算关系
        confBdPlatfromRela.setAuditSts(0);//待审核
        confBdPlatfromRela.setBdCode(request.getBdCode());//BDcode
        confBdPlatfromRela.setBdName(request.getBdName());//BD部门
        relaMapper.insertSelective(confBdPlatfromRela);
        //插入到BD部门表中
        ConfBd confBd = new ConfBd();
        BeanUtils.copyProperties(request, confBd);
        confBd.setCode(request.getBdCode());//BDcode
        confBd.setName(request.getBdName());//BD部门
        confBdMapper.insertSelective(confBd);
        //插入到申请表
        ConfPlatformApply confPlatformApply = new ConfPlatformApply();
        BeanUtils.copyProperties(request, confPlatformApply);
        confPlatformApply.setCode(code);
        confPlatformApply.setCurrentAction(0);
        confPlatformApply.setAuditSts(-1);
        confPlatformApply.setDeptId(request.getAdminOperate().getDeptId());
	 int flag = applyMapper.insertSelective(confPlatformApply);
	 if (flag == 1) {
	   return 1;
	 }else {
	   throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增失败");
	 }
	}


	/**
	 * 保存或修改记录信息
	 * @param request 需要保存的入参实体类
	 * @return int 是否保存或修改成功
	 * author tzc
	 * @date 2020-3-11 20:54:09
	 */
	@Override
	public int saveOrUpdate(ConfPlatform request){
		log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
		try {
			if (request == null) {
				throw new AppRuntimeException(ResponseCode.EXCEPTION,"入参为空");
			}
			if (request.getId() != null) {
				request.setUpdater(request.getAdminOperate().getOperator());//更新用户—当前登陆用户id
				request.setUpdateTime(new Date());//更改时间 获取系统当前时间
				log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
                //主表逻辑删除-------插入到申请表中
                deleteByPrimaryKeyLogically(request);
                //插入到申请表中
                ConfPlatformApply confPlatformApply = new ConfPlatformApply();
                BeanUtils.copyProperties(request, confPlatformApply);
                confPlatformApply.setCurrentAction(1);
                confPlatformApply.setDeleteFlag(0);
                confPlatformApply.setAuditSts(0);
				int flag = applyMapper.insertSelective(confPlatformApply);
				if(flag == 1){
				  return 1;
				}
			}else{
				request.setCreator(request.getAdminOperate().getOperator());//创建用户—当前登陆用户id
				request.setCreateTime(new Date());//创建时间 获取系统当前时间
				request.setCreator(request.getAdminOperate().getOperator());
				log.info("保存或修改记录信息，保存，入参 = {}", JSONObject.toJSONString(request));
                //平台编码默认生成
                Date date = new Date();
                //设置要获取到什么样的时间
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
                //获取String类型的时间
                String format = sdf.format(date);
                String code = "PF" + format;
                //插入到BD部门和平台关联列表
                ConfBdPlatfromRela confBdPlatfromRela = new ConfBdPlatfromRela();
                BeanUtils.copyProperties(request, confBdPlatfromRela);
                confBdPlatfromRela.setPlatformCode(code);//平台编码
                confBdPlatfromRela.setPlatformName(request.getName());//平台
                confBdPlatfromRela.setDeleteFlag(0);
                confBdPlatfromRela.setType(2);//结算关系
                confBdPlatfromRela.setAuditSts(0);//待审核
                confBdPlatfromRela.setBdCode(request.getBdCode());//BDcode
                confBdPlatfromRela.setBdName(request.getBdName());//BD部门
                relaMapper.insertSelective(confBdPlatfromRela);
                //插入到BD部门表中
                ConfBd confBd = new ConfBd();
                BeanUtils.copyProperties(request, confBd);
                confBd.setCode(request.getBdCode());//BDcode
                confBd.setName(request.getBdName());//BD部门
                confBdMapper.insertSelective(confBd);
                //插入到申请表
                ConfPlatformApply confPlatformApply = new ConfPlatformApply();
                BeanUtils.copyProperties(request, confPlatformApply);
                confPlatformApply.setCode(code);
                confPlatformApply.setCurrentAction(0);
                confPlatformApply.setAuditSts(0);
				int flag = applyMapper.insertSelective(confPlatformApply);
				if(flag == 1){
				  return 1;
				}else{
				  throw new AppRuntimeException(ResponseCode.EXCEPTION,"修改失败");
				}
			}
		} catch (Exception e) {
			log.error("用户保存或修改失败", e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"用户保存或修改失败");
		}
	     return -1;
	}

    @Override
    public int saveOrUpdateAudit(ConfPlatform request) {
        log.info("保存或修改记录信息，入参 = {}", JSONObject.toJSONString(request));
        try {
            if (request == null) {
                throw new AppRuntimeException(ResponseCode.EXCEPTION,"入参为空");
            }
            if (request.getId() != null) {
                log.info("保存或修改记录信息，修改，入参 = {}", JSONObject.toJSONString(request));
                int flag = mapper.updateByPrimaryKeyApply(request);
                if(flag == 1){
                    return 1;
                }
            }
        } catch (Exception e) {
            log.error("用户保存或修改失败", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION,"用户保存或修改失败");
        }
        return -1;
    }


    /**
	 * 删除记录
	 *
	 * @param request 需要删除,含有主键的入参实体类
	 * @return int 是否删除成功
	 */
	@Override
	public int deleteByPrimaryKey(ConfPlatform request) {
		int flag = mapper.deleteByPrimaryKey(request);
	    if (flag == 1) {
	      return 1;
	    }else {
	      throw new AppRuntimeException(ResponseCode.EXCEPTION, "删除失败");
	    }
	}


	/**
	 * 逻辑删除记录
	 *
	 * @param request 含有主键的逻辑删除实体类
	 * @return int 是否逻辑删除成功
	 */
	@Override
	public int deleteByPrimaryKeyLogically(ConfPlatform request) {
		request.setDeleteFlag(1);
		int flag = mapper.updateByPrimaryKey(request);
	    if (flag == 1) {
	      return 1;
	    }else {
	      throw new AppRuntimeException(ResponseCode.EXCEPTION, "逻辑删除记录失败");
	    }
	}


	/**
	 * 修改
	 *
	 * @param request
	 * @return
	 */
	@Override
	public int updateByPrimaryKeySelective(ConfPlatform request){
		try {
			log.info("修改记录");
			ConfPlatform param = new ConfPlatform();
			BeanUtils.copyProperties(request, param);
			int flag = mapper.updateByPrimaryKeySelective(param);
	        if (flag == 1) {
	         return 1;
	        }else {
	          throw new AppRuntimeException(ResponseCode.EXCEPTION, "修改记录失败");
	        }
		} catch (Exception e) {
			log.error("修改记录失败", e);
			throw new AppRuntimeException(ResponseCode.EXCEPTION,"修改记录失败");
		}

	}

	/**
	 * 记录详情
	 *
	 * @param request 查询的入参实体类
	 * @return 数据库查询到的实体类
	 */
	@Override
	public ConfPlatform getByPrimaryKey(ConfPlatform request) {
		return mapper.selectByPrimaryKey(request);
	}

	@Override
	public List<ConfFaultTreeResponse> selectFaultTree() {

		return mapper.selectFaultTree();
	}


	/**
	 * 分页查询
	 *
	 * @param request 分页查询入参实体类
	 * @return 含有分页信息的实体类列表
	 */
	@Override
	public PageInfo<ConfPlatform> listPageBySelective(ConfPlatform request, int pageNum, int pageSize) {
	PageHelper.startPage(pageNum, pageSize);
	PageHelper.orderBy(" update_time desc");
	List<ConfPlatform> list = mapper.listPageBySelective(request);
	PageInfo pageInfo = new PageInfo(list);
	PageResult<ConfPlatform> result = new PageResult<>();
	result.setTotal(pageInfo.getTotal());
	result.setRows(list);
	return new PageInfo(list);
	}
@Override
	public PageInfo<ConfPlatform> listPagefreeze(ConfPlatform request, int pageNum, int pageSize) {
	List<Integer> sts=new ArrayList<>();
	sts.add(-3);
	sts.add(-2);
	sts.add(2);
	PageHelper.startPage(pageNum, pageSize);
	PageHelper.orderBy(" create_time desc");
	List<ConfPlatform> list = mapper.listPagefreeze(sts);
	PageInfo pageInfo = new PageInfo(list);
	PageResult<ConfPlatform> result = new PageResult<>();
	result.setTotal(pageInfo.getTotal());
	result.setRows(list);
	return new PageInfo(list);
	}

	/**
	 * 不分页查询
	 *
	 * @param request 不分页查询入参实体类
	 * @return 数据库查到的实体类列表
	 */
	@Override
	public List<ConfPlatform> listAllRecord(ConfPlatform request) {
		//分页处理
		request.setDeleteFlag(0);
		return mapper.selectBySelective(request);
	}

	@Override
	public ConfPlatform getPlatformCode(String platformCode) {
		return mapper.getPlatformCode(platformCode);
	}

	@Override
	public List<ConfPlatform> getAlltPlatform() {
		return mapper.getAlltPlatform();
	}

    @Override
    public int insertSelective(ConfPlatform confPlatform) {
	    int flag = mapper.insertSelective(confPlatform);
        if(flag == 1 ){
            return  1;
        }else{
            throw new AppRuntimeException(ResponseCode.EXCEPTION, "新增失败");
        }

    }

	@Override
	public ConfPlatform getByPrimaryCode(ConfPlatform confPlatform) {
		return mapper.getByPrimaryCode(confPlatform);
	}

	@Override
	public List<ConfBdPlatfromRela> getPlatfromRela(ConfPlatform param) {
		return mapper.getPlatfromRela(param);
	}

	@Override
	public int activityRuleDeductionPoints(ConfActivityRule confActivityRule) {
		return mapper.activityRuleDeductionPoints(confActivityRule);
	}

	@Override
	public int insertPlatFromLog(ConfActivityRule confActivityRule) {
		return mapper.insertPlatFromLog(confActivityRule);
	}

	@Override//通过code查询 平台
	public List<ConfPlatform> selectByPrimaryCode(SignData signData) {
		return mapper.selectByPrimaryCode(signData);
	}

	@Override
	public BigDecimal queryAvailablePoint(String busiCode) {
		BigDecimal availablePoint= mapper.queryAvailablePoint(busiCode);
		return availablePoint;
	}

	@Override
	public int platformPointAdd(ConfPlatform confPlatform) {
		return mapper.platformPointAdd(confPlatform);
	}

	@Override
	public int platformPointDeduction(ConfPlatform confPlatform) {
		return mapper.platformPointDeduction(confPlatform);
	}


}
